package com.golxen.framework.common;


import com.golxen.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

public class ShutDownPlugin {

    static ShutDownPlugin instance = null;

    public static boolean startup = false;

    public static void start() {
        if (instance != null) {
            return;
        }

        instance = new ShutDownPlugin();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            long startTime = System.currentTimeMillis();
            LogUtil.CONSOLE.info("[ShutDownPlugin] shut down start.");

            for (int i = instance.fns.size() - 1; i >= 0; i--) {
                Runnable runnable = instance.fns.get(i);
                try {
                    runnable.run();
                } catch (Exception e) {
                    LogUtil.CONSOLE.error("", e);
                }
            }

            long endTime = System.currentTimeMillis();

            if (startup) {
                LogUtil.openAndCloseServerLog.info("notify process stop success!");
            }

            LogUtil.CONSOLE.info("[ShutDownPlugin] shut down end. {} ms", (endTime - startTime));

            org.apache.logging.log4j.LogManager.shutdown();
        }));

    }

    public static boolean active() {
        return instance != null;
    }

    public static void registShutDownFn(Runnable fn) {
        start();
        instance.fns.add(fn);
    }

    List<Runnable> fns = new ArrayList<>();

}
